package com.example.redislearning.controller;

import com.example.redislearning.dto.ApiResponse;
import com.example.redislearning.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 购物车控制器
 * 提供购物车的CRUD操作和合并功能
 */
@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public ApiResponse<String> addToCart(
            @RequestParam Integer userId,
            @RequestParam Integer courseId,
            @RequestParam(defaultValue = "1") Integer quantity) {
        try {
            boolean result = cartService.addToCart(userId, courseId, quantity);
            if (result) {
                return ApiResponse.success("商品添加成功", null);
            } else {
                return ApiResponse.error(400, "商品不存在或已下架");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "添加商品失败: " + e.getMessage());
        }
    }

    /**
     * 从购物车移除商品
     */
    @DeleteMapping("/remove")
    public ApiResponse<Void> removeFromCart(
            @RequestParam Integer userId,
            @RequestParam Integer courseId) {
        try {
            boolean result = cartService.removeFromCart(userId, courseId);
            if (result) {
                return ApiResponse.success("商品移除成功", null);
            } else {
                return ApiResponse.error(404, "商品不在购物车中");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "移除商品失败: " + e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/update")
    public ApiResponse<Void> updateCartItem(
            @RequestParam Integer userId,
            @RequestParam Integer courseId,
            @RequestParam Integer quantity) {
        try {
            if (quantity < 0) {
                return ApiResponse.error(400, "数量不能为负数");
            }

            boolean result = cartService.updateCartItemQuantity(userId, courseId, quantity);
            if (result) {
                return ApiResponse.success("商品更新成功", null);
            } else {
                return ApiResponse.error(400, "商品不存在或已下架");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "更新商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取购物车内容
     */
    @GetMapping("/items")
    public ApiResponse<Map<String, Object>> getCartItems(@RequestParam Integer userId) {
        try {
            Map<String, Object> cartItems = cartService.getCartItems(userId);
            return ApiResponse.success( "购物车获取成功",cartItems);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取购物车失败: " + e.getMessage());
        }
    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/clear")
    public ApiResponse<Void> clearCart(@RequestParam Integer userId) {
        try {
            cartService.clearCart(userId);
            return ApiResponse.success( "购物车清空成功",null);
        } catch (Exception e) {
            return ApiResponse.error(500, "清空购物车失败: " + e.getMessage());
        }
    }

    /**
     * 获取购物车商品数量
     */
    @GetMapping("/count")
    public ApiResponse<Integer> getCartItemCount(@RequestParam Integer userId) {
        try {
            int count = cartService.getCartItemCount(userId);
            return ApiResponse.success( "购物车商品数量获取成功",count);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取购物车商品数量失败: " + e.getMessage());
        }
    }

    /**
     * 合并临时购物车到用户购物车
     */
    @PostMapping("/merge")
    public ApiResponse<Void> mergeCart(
            @RequestParam Integer userId,
            @RequestBody Map<String, Integer> tempCartItems) {
        try {
            if (tempCartItems == null || tempCartItems.isEmpty()) {
                return ApiResponse.success("无临时购物车需要合并",null);
            }

            // 转换Map类型
            Map<Integer, Integer> items = new HashMap<>();
            for (Map.Entry<String, Integer> entry : tempCartItems.entrySet()) {
                try {
                    Integer courseId = Integer.valueOf(entry.getKey());
                    Integer quantity = entry.getValue();
                    if (quantity > 0) {
                        items.put(courseId, quantity);
                    }
                } catch (NumberFormatException e) {
                    // 跳过无效的courseId
                }
            }

            boolean result = cartService.mergeCart(userId, items);
            if (result) {
                return ApiResponse.success( "购物车合并成功",null);
            } else {
                return ApiResponse.error(500, "购物车合并失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "合并购物车失败: " + e.getMessage());
        }
    }

    /**
     * 检查商品是否在购物车中
     */
    @GetMapping("/contains")
    public ApiResponse<Boolean> isInCart(
            @RequestParam Integer userId,
            @RequestParam Integer courseId) {
        try {
            boolean result = cartService.isInCart(userId, courseId);
            return ApiResponse.success("检查成功",result);
        } catch (Exception e) {
            return ApiResponse.error(500, "检查失败: " + e.getMessage());
        }
    }

    /**
     * 获取无效购物车商品
     */
    @GetMapping("/invalid-items")
    public ApiResponse<Map<Integer, Integer>> getInvalidCartItems(@RequestParam Integer userId) {
        try {
            Map<Integer, Integer> invalidItems = cartService.getInvalidCartItems(userId);
            return ApiResponse.success( "无效商品获取成功",invalidItems);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取无效商品失败: " + e.getMessage());
        }
    }

    /**
     * 移除无效购物车商品
     */
    @DeleteMapping("/remove-invalid")
    public ApiResponse<Void> removeInvalidItems(@RequestParam Integer userId) {
        try {
            cartService.removeInvalidItems(userId);
            return ApiResponse.success( "无效商品移除成功",null);
        } catch (Exception e) {
            return ApiResponse.error(500, "移除无效商品失败: " + e.getMessage());
        }
    }

    /**
     * 批量操作购物车
     */
    @PostMapping("/batch")
    public ApiResponse<Void> batchOperation(
            @RequestParam Integer userId,
            @RequestBody Map<String, Object> operations) {
        try {
            String action = (String) operations.get("action");
            Map<String, Integer> items = (Map<String, Integer>) operations.get("items");

            if (action == null || items == null) {
                return ApiResponse.error(400, "参数不完整");
            }

            switch (action) {
                case "add":
                    for (Map.Entry<String, Integer> entry : items.entrySet()) {
                        Integer courseId = Integer.valueOf(entry.getKey());
                        Integer quantity = entry.getValue();
                        cartService.addToCart(userId, courseId, quantity);
                    }
                    break;
                case "update":
                    for (Map.Entry<String, Integer> entry : items.entrySet()) {
                        Integer courseId = Integer.valueOf(entry.getKey());
                        Integer quantity = entry.getValue();
                        cartService.updateCartItemQuantity(userId, courseId, quantity);
                    }
                    break;
                case "remove":
                    for (String courseIdStr : items.keySet()) {
                        Integer courseId = Integer.valueOf(courseIdStr);
                        cartService.removeFromCart(userId, courseId);
                    }
                    break;
                default:
                    return ApiResponse.error(400, "无效的操作类型");
            }

            return ApiResponse.success("批量操作成功", null);
        } catch (Exception e) {
            return ApiResponse.error(500, "批量操作失败: " + e.getMessage());
        }
    }
}